﻿using System;
using log4net;

namespace Messenia.ExceptionHandler {
    public class ExceptionManager {
        public class Handling {
            private static readonly ILog logger;
            static Handling () {
                //configure for log4net
                log4net.Config.XmlConfigurator.Configure ();
                //get the appenders for log
                logger = LogManager.GetLogger ("LogFileAppender");
            }

            /// <summary>
            /// Log the exception generated by the application
            /// </summary>
            /// <param name="ex"></param>
            /// <param name="user"></param>
            public static void ProcessException (ApplicationException ex, int user) {
                //get the base exception message

                Exception baseExc = ex.InnerException.GetBaseException ();
                string baseExcMessage = baseExc.Message;
                //get the inner exception
                Exception innerException = ex.InnerException;
                string innerExcMessage = "";
                if ( innerException != null ) {
                    innerExcMessage = innerException.Message;
                }
                //create the error message
                string layoutMessage = " - An exception occured : " + Environment.NewLine +
                                       " Message : " + ex.Message + Environment.NewLine +
                                       " Stack trace:" + ex.StackTrace + Environment.NewLine +
                                       " Inner exception message: " + innerExcMessage + Environment.NewLine +
                                       " Base exception message: " + baseExcMessage + Environment.NewLine +
                                        user +
                                       " -----------------------------------------------------------------------"

                                       + Environment.NewLine;

                //write the message in a log file
                logger.Error (layoutMessage);

                //send an error message to the client
                string clientErrorMessage = "Messenia cannot make the requested operation!";
                throw new ApplicationException (clientErrorMessage);
            }
        }
    }
}
